package edu.spec.wechat.web.filter;

import edu.spec.pms.model.student.Student;
import edu.spec.pms.service.iface.IStudentService;
import edu.spec.wechat.kit.WechatKit;
import edu.spec.wechat.model.WechatFianlValue;
import edu.spec.wechat.web.BeanFactoryContext;
import edu.spec.wechat.web.WechatContext;
import org.madgecko.basic.kit.BasicKit;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * Created by MadFrog on 2016/11/4.
 */
public class WechatAuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /**
         * Http请求总体分3种
         * A.微信消息
         * B.微信浏览器消息
         * C.常规浏览器消息
         */
        HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
        String agent = httpRequest.getHeader("User-Agent");
        Object user = httpRequest.getSession().getAttribute("user");
        String url = httpRequest.getRequestURI();

        System.out.println(url);
        System.out.println(agent);

        // A 微信消息、静态资源、登录请求直接pass
        if (url.indexOf("resources")>0 || url.indexOf("wechatpms")>0 || url.indexOf("login")>0 || url.indexOf("bindingStudent")>0){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //检查用户是否登录
        if (user==null){
            System.out.println(agent);
            // B 微信浏览器端的请求
            if (agent!=null && agent.toLowerCase().indexOf("micromessenger")>=0){
                String code = servletRequest.getParameter("code");
                String state = servletRequest.getParameter("state");
                System.out.println("code & state : " + code + ", " + state);
                if (code!=null&&state!=null&&state.equals("1")){
                    //微信端跳转以后，code和state都有了。
                    String openId = WechatKit.getOpenIdByCode(code);
                    System.out.println("openId : " + openId);
                    IStudentService studentService = (IStudentService) BeanFactoryContext.getService("studentService");
                    Student student = studentService.loadByOpenId(openId);
                    httpRequest.getSession().setAttribute("user", student);
                    httpRequest.getSession().setAttribute("openId", openId);
                } else {
                    //第一次访问链接的时候，code、state都为空。
                    String path = httpRequest.getRequestURL().toString();
                    String query = httpRequest.getQueryString();
                    if(!BasicKit.isEmpty(query)){
                        path += "?" + query;
                    }
                    String uri = WechatFianlValue.AUTH_GET_CODE;
                    uri = uri.replace("APPID", WechatContext.getInstance().getAppID())
                            .replace("REDIRECT_URI", URLEncoder.encode(path, "UTF-8"))
                            .replace("SCOPE", "snsapi_base")
                            .replace("STATE", "1");
                    System.out.println(path);
                    httpResponse.sendRedirect(uri);
                    System.out.println("httpResponse.sendRedirect(uri) : " + uri);
                    return;
                }
            // C 普通浏览器请求
            }
//            else {
//                if(!(url.indexOf("binding")>0)){
//                    httpResponse.sendRedirect(httpRequest.getContextPath()+"/login");
//                    return;
//                }
//            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
